package com.example.changtest.blankfragment;

import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @author: zcs
 * @email: 1059737741@qq.com
 * create at 2022/1/28 10:55
 */
public class WXApiHelp {
    private static final String REQUEST_CAPTURE = "request_capture";
    private WeakReference<FragmentActivity> mWeakActivityRef;
    private static WXApiHelp instance;

    public static WXApiHelp getInstance() {
        if (instance == null) {
            synchronized (WXApiHelp.class) {
                if (instance == null) {
                    instance = new WXApiHelp();
                }
            }
        }
        return instance;
    }

    public WXApiHelp init(FragmentActivity activity){
        mWeakActivityRef = new WeakReference<>(activity);
        return instance;
    }

    private RouterFragment getFragment(){

        FragmentManager manager = mWeakActivityRef.get().getSupportFragmentManager();
        RouterFragment fragment = (RouterFragment)manager.findFragmentByTag(REQUEST_CAPTURE);

        if(fragment == null){
            fragment = RouterFragment.getInstance();
            manager.beginTransaction()
                    .add(fragment,REQUEST_CAPTURE)
                    .commitAllowingStateLoss();
            manager.executePendingTransactions();
        }

        return fragment;
    }

    public void release(){

        if(mWeakActivityRef != null && mWeakActivityRef.get() != null){

            FragmentManager manager = mWeakActivityRef.get().getSupportFragmentManager();
            RouterFragment fragment = (RouterFragment)manager.findFragmentByTag(REQUEST_CAPTURE);

            if(fragment != null){
                fragment = RouterFragment.getInstance();
                manager.beginTransaction()
                        .remove(fragment)
                        .commitAllowingStateLoss();
                manager.executePendingTransactions();
            }
            instance = null;
            mWeakActivityRef.clear();
        }
    }


    public void wxLogin(RouterWXCallBack routerWXCallBack){
        getFragment().wxLogin(new WXCallBack() {
            @Override
            public void callBack(String callBack) {
                Map<String,String> map = new HashMap<>();
                if (null != routerWXCallBack){
                    routerWXCallBack.callBack(map);
                }
            }
        });
    }

    public interface WXCallBack{
        void callBack(String callBack);
    }
}
